package org.example.factory.bean;

import org.example.cache.RedisUtil;
import org.example.controller.CounterController;
import org.example.dto.CounterDto;
import org.example.factory.Counter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @FileName CommentCounter
 * @Description
 * @Author coderfun
 * @selfDesc coding in fun
 * @date 2024-11-02
 **/
@Component
public class CommentCounter implements Counter {
    @Resource
    private RedisUtil redisUtil;
    private static final Logger logger = LoggerFactory.getLogger(CounterController.class);
    private final static String prefix = "comment";
    private final static String busi = "counter";

    @Override
    public Boolean add(CounterDto counterDto) {
        try {
            //TODO 添加记录数的时候，还要维护用户与点赞的关系（一对多的关系）维护LUA脚本保证事务
            logger.info(prefix + ":add,id:{},kind:{}", counterDto.getId(), counterDto.getKind());
            String currentCountStr = (String) redisUtil.hGet(busi + "_" + counterDto.getId(), prefix);
            Integer currentCount = currentCountStr != null ? Integer.parseInt(currentCountStr) : 0;
            int newCount = currentCount + 1;
            redisUtil.hPut(busi + "_" + counterDto.getId(), prefix, String.valueOf(newCount));
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public Boolean sub(CounterDto counterDto) {
        try {
            logger.info(prefix + ":sub,id:{},kind:{}", counterDto.getId(), counterDto.getKind());
            String currentCountStr = (String) redisUtil.hGet(busi + "_" + counterDto.getId(), prefix);
            Integer currentCount = currentCountStr != null ? Integer.parseInt(currentCountStr) : 0;
            int newCount = currentCount - 1;
            redisUtil.hPut(busi + "_" + counterDto.getId(), prefix, String.valueOf(newCount));
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public Integer select(CounterDto counterDto) {
        try {
            logger.info(prefix + ":select,select:{},kind:{}", counterDto.getId(), counterDto.getKind());
            String currentCountStr = (String) redisUtil.hGet(busi + "_" + counterDto.getId(), prefix);
            Integer currentCount = currentCountStr != null ? Integer.parseInt(currentCountStr) : 0;
            return currentCount;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
}
